import { fileURLToPath, URL } from 'node:url';

import vue from '@vitejs/plugin-vue';
import { defineConfig, loadEnv } from 'vite';
import { viteStaticCopy } from 'vite-plugin-static-copy';

export default defineConfig(({ mode }) => {
  // 关键修改：加载环境变量（兼容 .env.dev）

  const env = loadEnv(mode, process.cwd(), '');

  return {
    build: {
      minify: 'terser',
      terserOptions: {
        compress: {
          drop_console: true, // 移除所有 console
          // 或者精确控制：
          // pure_funcs: ['console.log', 'console.debug']
        },
        format: {
          comments: false, // 移除注释
        },
      },
    },
    optimizeDeps: {
      // exclude: ['cesium'], // 避免 Vite 错误地优化 Cesium
    },
    plugins: [
      vue(),
      viteStaticCopy({
        targets: [
          {
            src: 'node_modules/cesium/Build/Cesium/Workers/*',
            dest: 'Workers',
          },
          {
            src: 'node_modules/cesium/Build/Cesium/ThirdParty/*',
            dest: 'ThirdParty',
          },
          {
            src: 'node_modules/cesium/Build/Cesium/Assets/*',
            dest: 'Assets',
          },
          {
            src: 'node_modules/cesium/Build/Cesium/Widgets/*',
            dest: 'Widgets',
          },
        ],
      }),
    ],
    resolve: {
      alias: {
        '@': fileURLToPath(new URL('./src', import.meta.url)),
      },
    },
    css: {
      preprocessorOptions: {
        scss: {
          api: 'modern-compiler',
          javascriptEnabled: true,
          additionalData: '@use "@/styles/variable.scss" as *;',
        },
      },
    },
    server: {
      port: 5055,
      proxy: {
        '/api': {
          target: `http://${env.VITE_PROXY_IP}:8088`, // 从 env 读取
          changeOrigin: true,
          rewrite: (path) => path.replace(/^\/api/, ''),
        },
      },
    },
    useEslint: false,
  };
});
